<!-- 三级医院报销比例管理 -->
<template>
  <div class="ratio-flex-center">
    <div class="ratio-card ratio-table-card">
      <div class="ratio-title">
        三级医院报销比例列表
        <el-button @click="$router.push('/medical-info/hospital-ratio')" type="text" class="back-btn">
          返回概览
        </el-button>
      </div>
      
      <div class="table-header">
        <el-button type="primary" @click="handleAdd" class="add-btn" size="large">+ 新增</el-button>
        <div class="search-filters">
          <el-select v-model="searchForm.personType" placeholder="人员类型" clearable @change="handleSearch" class="filter-select">
            <el-option label="在职" value="在职" />
            <el-option label="退休" value="退休" />
          </el-select>
          <el-select v-model="searchForm.staus" placeholder="状态筛选" clearable @change="handleSearch" class="filter-select">
            <el-option label="全部" value="" />
            <el-option label="启用" value="启用" />
            <el-option label="停用" value="停用" />
          </el-select>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
      
      <el-table :data="tableData" class="ratio-table" border v-loading="loading">
        <el-table-column prop="personType" label="人员类型" align="center" width="120"/>
        <el-table-column label="费用区间" align="center" width="180">
          <template #default="{ row }">
            {{ formatCostRange(row.costMin, row.costMax) }}
          </template>
        </el-table-column>
        <el-table-column prop="reimbursementRatio" label="报销比例(%)" align="center" width="140">
          <template #default="{ row }">
            {{ row.reimbursementRatio }}%
          </template>
        </el-table-column>
        <el-table-column prop="staus" label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.staus === '启用' ? 'success' : 'info'">{{ row.staus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <div class="ratio-card ratio-form-card">
      <div class="ratio-title">
        {{ isEdit ? '编辑' : '新增' }}报销比例
        <span class="tip">人员类型和费用区间不可重复</span>
      </div>
      
      <el-form 
        :model="form" 
        :rules="formRules"
        ref="formRef"
        label-width="120px" 
        class="ratio-form"
      >
        <el-form-item label="人员类型" prop="personType">
          <el-select v-model="form.personType" placeholder="请选择人员类型" style="width: 100%;">
            <el-option label="在职" value="在职" />
            <el-option label="退休" value="退休" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="费用区间下限" prop="costMin">
          <el-input-number
            v-model="form.costMin"
            :min="0"
            :precision="2"
            style="width: 100%;"
            placeholder="请输入费用区间下限"
          />
          <div class="form-tip">单位：元</div>
        </el-form-item>
        
        <el-form-item label="费用区间上限" prop="costMax">
          <el-input-number
            v-model="form.costMax"
            :min="0"
            :precision="2"
            style="width: 100%;"
            placeholder="请输入费用区间上限"
          />
          <div class="form-tip">单位：元，必须大于下限</div>
        </el-form-item>
        
        <el-form-item label="报销比例" prop="reimbursementRatio">
          <el-input-number
            v-model="form.reimbursementRatio"
            :min="0"
            :max="100"
            :precision="2"
            style="width: 100%;"
            placeholder="请输入报销比例"
          />
          <div class="form-tip">范围：0-100%</div>
        </el-form-item>
        
        <el-form-item label="状态" prop="staus">
          <el-radio-group v-model="form.staus">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="停用">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <div class="form-buttons">
            <div class="primary-buttons">
              <el-button type="primary" @click="handleSubmit" class="form-btn" :loading="submitLoading">
                {{ isEdit ? '更新' : '保存' }}
              </el-button>
              <el-button @click="handleReset" class="form-btn">重置</el-button>
            </div>
            <div v-if="isEdit" class="secondary-buttons">
              <el-button @click="handleCancel" class="form-btn cancel-btn">取消编辑</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getHospitalRatioPage, 
  addHospitalRatio, 
  updateHospitalRatio, 
  deleteHospitalRatio,
  updateHospitalRatioStatus 
} from '@/api/hospitalRatio'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const tableData = ref([])
const total = ref(0)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 10,
  hospitalLevel: '三', // 固定为三级医院
  personType: '',
  staus: '',
  minRatio: null,
  maxRatio: null
})

// 编辑表单
const form = reactive({
  ratioId: null,
  hospitalLevel: '三',
  personType: '',
  costMin: 0,
  costMax: 0,
  staus: '启用',
  reimbursementRatio: 0
})

// 表单验证规则
const formRules = {
  personType: [
    { required: true, message: '请选择人员类型', trigger: 'change' }
  ],
  costMin: [
    { required: true, message: '请输入费用区间下限', trigger: 'blur' },
    { type: 'number', min: 0, message: '费用不能小于0', trigger: 'blur' }
  ],
  costMax: [
    { required: true, message: '请输入费用区间上限', trigger: 'blur' },
    { type: 'number', min: 0, message: '费用不能小于0', trigger: 'blur' }
  ],
  reimbursementRatio: [
    { required: true, message: '请输入报销比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '报销比例范围为0-100', trigger: 'blur' }
  ],
  staus: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 格式化费用区间
const formatCostRange = (min, max) => {
  if (min == null && max == null) return '-'
  if (min == null) return `≤ ${max}`
  if (max == null) return `≥ ${min}`
  return `${min} - ${max}`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    console.log('加载三级医院报销比例数据，查询参数：', searchForm)
    
    const response = await getHospitalRatioPage(searchForm)
    console.log('三级医院报销比例响应：', response)
    
    if (response.flag && response.data) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.warning(response.message || '数据加载失败')
    }
  } catch (error) {
    console.error('加载三级医院报销比例失败：', error)
    ElMessage.error('数据加载失败：' + error.message)
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  searchForm.personType = ''
  searchForm.staus = ''
  searchForm.minRatio = null
  searchForm.maxRatio = null
  searchForm.pageNum = 1
  resetForm()
  loadData()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  resetForm()
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  form.ratioId = row.ratioId
  form.hospitalLevel = row.hospitalLevel
  form.personType = row.personType
  form.costMin = row.costMin
  form.costMax = row.costMax
  form.staus = row.staus
  form.reimbursementRatio = row.reimbursementRatio
  
  // 清除表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return

    // 验证费用区间
    if (form.costMin >= form.costMax) {
      ElMessage.warning('费用区间上限必须大于下限')
      return
    }

    // 检查重复配置（排除当前编辑的记录）
    const duplicate = tableData.value.find(item => 
      item.personType === form.personType && 
      item.costMin === form.costMin &&
      item.costMax === form.costMax &&
      (!isEdit.value || item.ratioId !== form.ratioId)
    )
    
    if (duplicate) {
      ElMessage.warning(`人员类型"${form.personType}"的费用区间"${form.costMin}-${form.costMax}"已存在，请修改费用区间`)
      return
    }

    submitLoading.value = true

    const submitData = {
      hospitalLevel: form.hospitalLevel,
      personType: form.personType,
      costMin: form.costMin,
      costMax: form.costMax,
      staus: form.staus,
      reimbursementRatio: form.reimbursementRatio
    }

    if (isEdit.value) {
      submitData.ratioId = form.ratioId
    }

    console.log('提交数据：', submitData)

    const response = isEdit.value 
      ? await updateHospitalRatio(submitData)
      : await addHospitalRatio(submitData)

    console.log('保存响应：', response)

    if (response.flag) {
      ElMessage.success(response.message || `${isEdit.value ? '更新' : '新增'}成功`)
      resetForm()
      loadData()
    } else {
      ElMessage.error(response.message || `${isEdit.value ? '更新' : '新增'}失败`)
    }
  } catch (error) {
    console.error('保存失败：', error)
    ElMessage.error('保存失败：' + error.message)
  } finally {
    submitLoading.value = false
  }
}

// 删除操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除该报销比例吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteHospitalRatio(row.ratioId)
    
    if (response.flag) {
      ElMessage.success(response.message || '删除成功')
      loadData()
      
      // 如果删除的是当前编辑的记录，重置表单
      if (isEdit.value && form.ratioId === row.ratioId) {
        resetForm()
      }
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 重置表单
const resetForm = () => {
  form.ratioId = null
  form.hospitalLevel = '三'
  form.personType = ''
  form.costMin = 0
  form.costMax = 0
  form.staus = '启用'
  form.reimbursementRatio = 0
  isEdit.value = false
  
  // 清除表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 取消编辑
const handleCancel = () => {
  resetForm()
}

// 分页处理
const handleSizeChange = (newSize) => {
  searchForm.pageSize = newSize
  searchForm.pageNum = 1
  loadData()
}

const handleCurrentChange = (newPage) => {
  searchForm.pageNum = newPage
  loadData()
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.ratio-flex-center {
  display: flex;
  justify-content: stretch;
  align-items: flex-start;
  gap: 40px;
  min-height: 100vh;
  padding: 48px 40px 0 40px;
  background: #f7f8fa;
  width: 100%;
  box-sizing: border-box;
}

.ratio-card {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  padding: 32px 36px 28px 36px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.ratio-table-card {
  flex: 2;
  min-width: 0;
  margin-top: 0;
}

.ratio-form-card {
  flex: 1;
  min-width: 400px;
  max-width: 500px;
  margin-top: 0;
}

.ratio-title {
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 24px;
  color: #303133;
  position: relative;
}

.back-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
  color: #909399;
}

.back-btn:hover {
  color: #409eff;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

.add-btn {
  font-size: 16px;
  border-radius: 6px;
  padding: 12px 24px;
}

.search-filters {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-select {
  width: 120px;
}

.ratio-table {
  background: #fff;
  font-size: 14px;
}

.ratio-table :deep(.el-table__cell) {
  min-height: 48px;
  height: 48px;
  line-height: 48px;
  font-size: 14px;
}

.ratio-table :deep(.el-table__header-wrapper .el-table__header) {
  background-color: #fafafa;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.tip {
  color: #f56c6c;
  font-size: 14px;
  font-weight: normal;
  margin-left: 8px;
}

.ratio-form {
  margin-top: 8px;
}

.form-btn {
  min-width: 80px;
  font-size: 14px;
  border-radius: 6px;
  margin-right: 12px;
}

.form-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.primary-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.secondary-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
}

.cancel-btn {
  color: #909399;
  border-color: #dcdfe6;
  margin-right: 0;
}

.cancel-btn:hover {
  color: #f56c6c;
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.2;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .ratio-flex-center {
    flex-direction: column;
    gap: 20px;
    padding: 20px;
  }
  
  .ratio-form-card {
    max-width: none;
    min-width: 0;
  }
}

@media (max-width: 768px) {
  .ratio-flex-center {
    padding: 16px 12px;
  }
  
  .ratio-card {
    padding: 20px 16px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .add-btn {
    width: 100%;
  }
  
  .search-filters {
    width: 100%;
    justify-content: space-between;
  }
  
  .filter-select {
    flex: 1;
    width: auto;
  }
  
  .primary-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-btn {
    width: 100%;
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .secondary-buttons .form-btn {
    margin-bottom: 0;
  }
  
  .back-btn {
    position: static;
    transform: none;
    margin-top: 8px;
  }
  
  .ratio-title {
    text-align: left;
  }
}
</style>
